import {computed} from "vue";

const cache = new Map();

const refCache = new Map();

export function computedClearAll() {
    cache.clear();
    refCache.clear();
}
export function useComputed(fn) {
    function clearIfToBig() {
        if (cache.size > 500) {
            cache.clear();
        }
    }

    return function (...args) {
        let key = JSON.stringify(args);
        clearIfToBig();
        return cache.get(key) || cache.set(key, fn(...args)).get(key);
    }
}

export function useComputedRef(fn) {

    function clearIfToBig() {
        if (cache.size > 500) {
            refCache.clear();
        }
    }

    return function (...args) {
        let key = JSON.stringify(args);
        clearIfToBig();
        return refCache.get(key) || refCache.set(key, computed(() => fn(...args))).get(key);
    }
}
